package com.sskj.api.config;

import com.sskj.api.properties.FileProperties;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private FileProperties fileProperties;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
                .allowedHeaders("*")
                .exposedHeaders("Authorization", "Content-Disposition")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Override
    public void addResourceHandlers(@NotNull ResourceHandlerRegistry registry) {
        // 获取配置的上传目录
        String uploadDirConfig = fileProperties.getUploadDir();
        if (uploadDirConfig == null || uploadDirConfig.trim().isEmpty()) {
            throw new IllegalArgumentException("file.upload-dir 配置不能为空");
        }

        Path uploadPath = Paths.get(uploadDirConfig);

        // 如果是相对路径，基于当前工作目录转为绝对路径
        if (!uploadPath.isAbsolute()) {
            uploadPath = Paths.get("").toAbsolutePath().resolve(uploadPath);
        }

        // 规范化路径（处理 . 和 ..）
        uploadPath = uploadPath.normalize();

        // 确保目录存在
        try {
            Files.createDirectories(uploadPath);
        } catch (IOException e) {
            throw new IllegalStateException("无法创建上传目录: " + uploadPath, e);
        }

        // 转为字符串，统一使用正斜杠 /
        String normalizedPath = uploadPath.toString().replace("\\", "/");

        // 确保以 / 结尾
        if (!normalizedPath.endsWith("/")) {
            normalizedPath += "/";
        }

        String location = "file:/" + normalizedPath;

        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(location);
    }
}
